# -*- coding:utf-8 -*-
import os
import re
from PyQt5.QtWidgets import QFileDialog
from util.basic import read_file
from ui_base import Ui_Dialog


class ZhengzeUI(Ui_Dialog):
    
    def __init__(self):
        super().__init__()
        self._vars['zhengze'] = '1.1.0.0'
    
    def zhengze_init(self):
        """绑定卡片内事件响应"""
        self.zhengze_comboBox_encoding.addItems(['[Auto]', 'utf-8', 'gbk', 'gbk2312', 'ascii'])
        self.zhengze_button_run.clicked.connect(self.zhengze_button_run_down)
        self.zhengze_button_read_file.clicked.connect(self.zhengze_button_read_file_down)
        self.zhengze_comboBox_encoding.currentIndexChanged.connect(self.zhengze_comboBox_encoding_change)
    
    def zhengze_logic(self, text:str, req:str, I_flag:bool=False):
        """
        正则执行逻辑
        """
        try:
            last = re.findall(req, text, 0 if not I_flag else re.IGNORECASE)
            tip = '总共{}个结果:\n'.format(len(last))
            tip += '\n'.join(['{}'.format(res) for res in last])
        except Exception as e:
            tip = 'Error：{}'.format(str(e))
        return tip

    def zhengze_button_run_down(self):
        """执行按钮"""
        text = str(self.zhengze_textEdit_text.toPlainText())
        req = str(self.zhengze_lineEdit_re.text())
        I_flag = self.zhengze_checkBox_ignorecase.isChecked()
        every_line_flag = self.zhengze_checkBox_line_split.isChecked()
        if every_line_flag:
            texts = text.split('\n')
            tips = ''
            for i,text in enumerate(texts):
                tip = self.zhengze_logic(text, req, I_flag)
                tips += f'Line {i+1}.' + tip + '\n'
        else:
            tips = self.zhengze_logic(text, req, I_flag)
        self.zhengze_textEdit_return.setText(tips)
    
    def zhengze_button_read_file_down(self):
        """选择文件按钮"""
        _path = self.zhengze_lineEdit_filepath.text()
        if _path:
            _dir, _ = os.path.split(_path)
        else:
            _dir = os.getcwd()
        path, filetype = QFileDialog.getOpenFileName(parent=self.widget, caption='选择文件', 
                                                      directory=_dir,
                                                      filter='文本文件(*.txt; *.html; *.py; *.c; *.cpp; *.log; *.css; *.js; *.md; *.bat)')
        if not path:
            return
        self.zhengze_lineEdit_filepath.setText(path)
        self.zhengze_comboBox_encoding_change()
    
    def zhengze_comboBox_encoding_change(self):
        """编码下拉框改变事件"""
        path = self.zhengze_lineEdit_filepath.text()
        if not path:
            return        
        encoding = self.zhengze_comboBox_encoding.currentText()
        if encoding == '[Auto]':
            encoding = 'auto'
        res = read_file(path, encoding)
        self.zhengze_label_code.setText('未知' if res['encoding'] is None else res['encoding'])
        self.zhengze_textEdit_text.setPlainText(res['data'])    